import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;


public class SportsLeaderBoardView {
	
	/**
	 * @param args
	 */
	private String view;
	private String template;
	
	protected String getView() {
		return view;	
	}
	
	protected void setView(List<SportsLeaderBoardViewData> list) {
		String tableData = "";
		String mView = template;
		for (SportsLeaderBoardViewData d: list) {
			tableData += "<tr><td>"+d.getPlace()+"</td><td>"+d.getTrack()+"</td><td>"+d.getNumber()+"</td><td align=\"right\">"+d.getTime()+"</td></tr>\n";
		}
		view = mView.replaceFirst("TABLE_DATA", tableData);
	}

	public void init() {
		File aFile = new File("template.html");
		StringBuilder contents = new StringBuilder();	    
		try {
			BufferedReader input =  new BufferedReader(new FileReader(aFile));
			try {
				String line = null; //not declared within while loop
				while (( line = input.readLine()) != null){
					contents.append(line);
					contents.append(System.getProperty("line.separator"));
				}
			}
			finally {
				input.close();
			}
		}
	    catch (IOException ex){
	    	ex.printStackTrace();
	    }
	    template = contents.toString();
	    view = template;
	}
	
	public static void main(String[] args) {
		String comPort;
		String httpPort;
		if (args.length == 1) {
			comPort = args[0];  
			httpPort = "80";
		}
		else if (args.length == 2) {
			comPort = args[0];  
			httpPort = args[1];	
		} 
		else {
			System.out.println("Error: Wrong number of parameters.\nUsage: SportsLeaderBoardView com-port [http-port]");
			return;
		}
		
		
		SportsLeaderBoardView view = new SportsLeaderBoardView();
		view.init();
		SportsLeaderBoardSerial con = new SportsLeaderBoardSerial();
		SportsLeaderBoardHttp http = new SportsLeaderBoardHttp();
		
		try {
			con.start(comPort, view);
			http.startServer(Integer.parseInt(httpPort), view);
			
			//for (;;) {}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
